const db = wx.cloud.database();
import util from "../../utils/util.js"
// pages/Pay/Pay.js
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		address: {},
		carList: [],
		checkedCar: [],
		totalPrice: 0,
		total: 0
	},


	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		const carList = wx.getStorageSync("cart_detail");
		let totalPrice = 0;
		let total = 0;
		let checkedCar = carList.filter(v => v.Choose)
		checkedCar.forEach(v => {
			totalPrice += v.goods_price * v.num;
			total += v.num
		})
		this.setData({
			totalPrice,
			total,
			checkedCar
		});
	},

	onShow() {
		const address = wx.getStorageSync("address");
		const carList = wx.getStorageSync("cart_detail");
		this.setData({
			address,
			carList
		})
	},

	PayOfBuy() {
		const token = wx.getStorageSync("token");
		const userInfo = wx.getStorageSync("userInfo");
		if (!token) {
			wx.navigateTo({
				url: "/pages/author/author"
			})
			return;
		} else if (!userInfo) {
			wx.navigateTo({
				url: "/pages/login/login"
			})
		} else {
			const nowDate = util.formatTime(new Date());
			console.log(nowDate);
			db.collection('order_List').add({
					data: {
						orderName: this.data.address.userName,
						orderPhone: this.data.address.telNumber,
						orderAdress: this.data.address.allAddress,
						orderTime: nowDate,
						goods: this.data.checkedCar,
						totalPrice: this.data.totalPrice,
						type: 1
					}
				})
				.then((res) => {
					wx.showToast({
						title: "下单完成！",
						icon: "success",
						mask: true
					})
					let newcarList = wx.getStorageSync("cart_detail");
					newcarList = newcarList.filter(v => !v.Choose);
					wx.setStorageSync("cart_detail", newcarList);
					//页面出栈
					wx.redirectTo({
						url: "/pages/order/order?type=1"
					});
				})

		}
	}




})
